﻿using System;
using System.IO;
using System.Text;
using CodeGeneration.Model;
using CodeGeneration.Util;
using DotLiquid;

namespace CodeGeneration.TextEngine
{
    public class DotLiquidTextEngine:ITextEngine
    {
        public DotLiquidTextEngine()
        {
            Template.RegisterSafeType(typeof(EntityProperty),
                new[] {"Remark", "IsPrimaryKey", "CSharpType", "IsNullable", "Name"});
        }
        public void TransferText<T>(T model, string file)
        {
            var name = typeof(T).Name.ToLower();
            name = name.Substring(0, name.LastIndexOf("model", StringComparison.Ordinal));
            var templateText = GetTemplateText($"{name}.dotliquid");
            Template template = Template.Parse(templateText); 
            var result = template.Render(Hash.FromAnonymousObject(model)); 
            TemplateUtil.RenderStringToFile(result, file);
        }

        public string GetTemplateText(string file)
        {
            var rootDir = Environment.CurrentDirectory;
            var path = Path.Combine(rootDir, "Template\\DotLiquid", file);
            return File.ReadAllText(path, Encoding.UTF8);
        }
    }
}